from socket import *
import struct

def main():
    
    fileName = raw_input("please input you file:")
    require = struct.pack("!H%dsb5sb"%len(fileName), 1, fileName, 0, "octet",0)

    udp = socket(AF_INET, SOCK_DGRAM)
    udp.sendto(require, ('10.10.10.245', 69))

    d_f = open(fileName, 'w')
    num = 0

    while True:

        reBackDate = udp.recvfrom(1024)
        netDate, serInfo = reBackDate

        opNum = struct.unpack("!H", netDate[:2])
        nBlock = struct.unpack("!H", netDate[2:4])

        if opNum[0] == 3:
            num = num + 1

            if num == 65536:
                num = 1

            if nBlock[0] == num:
                d_f.write(netDate[4:])
                num = netDate[0]

            ackDate = struct.pack("!HH",4,num)
            udp.sendto(ackDate, serInfo)
        elif opNum[0] == 5:
            break

        if len(netDate) < 512:
            break

    d_f.flush()
    d_f.close()
    udp.close()

main()
